<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UsersAssets extends Model
{
    protected $table = 'users_assets_01';
    public $tableStr = 'users_assets_';
    public $timestamps = false; // 指示模型是否自动维护时间戳
    protected $dateFormat = 'U'; // 模型日期列的存储格式。

    protected function tables(){
        return array(
            'users_assets_01',
            'users_assets_02',
            'users_assets_03',
        );
    }

    /**
     * Todo:: 初始化的资产
     * @return array
     */
    public function initAssets(){
//        $data = array(
//            'canton_balance' => '坎通余额'
//        );
        $data = Assets::where([
            ['status','=',1],
            ['is_del','=',0],
        ])->pluck('name_alias','name')->toArray();
        return $data;
    }

    /**
     * Todo:: 获取表名称
     * @param $userId
     * @return bool|int|string
     */
    public function tableName($userId){
        $num = $userId%3;
        $string = $this->tableStr;
        if($num == 0){
            $string .= '03';
        }elseif($num>0 && $num < 10){
            $string .= '0'.$num;
        }elseif($num > 10){
            $string .= $num;
        }
        if(in_array($string,$this->tables())){
            $this->table = $string;
            return $string;
        }
        return false;
    }


    /**
     * Todo:: 创建初始化资产
     * @param $userId
     * @param string $tableName 表名称
     * @return bool
     */
    public function createInitAssets($userId,$tableName=''){
        if($tableName){
            $this->table = $tableName;
        }else{
            $this->tableName($userId);
        }
        $insertData = [];
        foreach($this->initAssets() as $key=>$val){
            $insertData[] = [
                'user_id' => $userId,
                'name' => $key,
                'name_alias' => $val,
                'total' => 0,
                'available' => 0,
                'freeze' => 0,
            ];
        }
        $result = DB::table($this->table)->insert($insertData);
        return $result;
    }




    /**
     * Todo:: 创建新资产
     * @param $userId
     * @param $data
     * @return bool
     */
    public function createNewAssets($userId,$data){
        $this->tableName($userId);
        $result = DB::table($this->table)->insert($data);
        return $result;
    }


    /**
     * Todo:: 判断用户资产是否存在
     * @param $userId
     * @param $assetsName
     * @return bool
     */
    public function isAssetsName($userId,$assetsName){
        $this->tableName($userId);
        $result = DB::table($this->table)->where([
            ['user_id','=',$userId],
            ['name','=',$assetsName],
        ])->exists();
        return $result;
    }

    /**
     * Todo:: 更新数据
     * @param $userId 用户ID
     * @param $assetsName 资产名称
     * @param $data total总数\available可用\freeze冻结
     * @return int
     */
    public function getUpdate($userId,$assetsName,$data){
        if(!$this->tableName($userId)){
            return false;
        }
        $result = DB::table($this->table)->where([
            ['user_id','=',$userId],
            ['name','=',$assetsName],
        ])->update($data);
        return $result;
    }

    /**
     * Todo:: 通过 ID 更新单个数据
     * @param $userId
     * @param $assetsId
     * @param $data
     * @return bool|int
     */
    public function getUpdateId($userId, $assetsId, $data)
    {
        if (!$this->tableName($userId)) {
            return false;
        }
        $result = DB::table($this->table)->where([
            ['user_id', '=', $userId],
            ['id', '=', $assetsId],
        ])->update($data);
        return $result;
    }



    /**
     * Todo:: 获取用户单个资产数据
     * @param $userId
     * @param $assetsName
     * @return Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function getAssetsName($userId,$assetsName){
        $this->tableName($userId);
        $result = DB::table($this->table)->where([
            ['user_id','=',$userId],
            ['name','=',$assetsName],
        ])->first();
        return $result;
    }

    /**
     * Todo:: 通过资产ID获取单哥资产数据
     * @param $userId
     * @param $assetsId
     * @return Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function getAssetsId($userId,$assetsId){
        $this->tableName($userId);
        $result = DB::table($this->table)->where([
            ['user_id','=',$userId],
            ['id','=',$assetsId],
        ])->first();
        return $result;
    }


    /**
     * Todo:: 用户资产列表
     * @param $userId
     * @param string $showType all 全部,show 正常显示
     * @return \Illuminate\Support\Collection
     */
    public function userAssetsList($userId,$showType='all'){
        if(!$this->tableName($userId)){
            return false;
        }
        if($showType == 'all'){
            $data =DB::table($this->table)->where('user_id',$userId)->get();
        }else{
            $data =DB::table($this->table)->where('user_id',$userId)->whereNull('deleted_at')->get();
        }
        return $data;
    }


    /**
     * Todo:: 软删除
     * @param $userId
     * @param string $tableName
     * @return int
     */
    public function updateDel($userId,$tableName=''){
        if($tableName){
            $this->table = $tableName;
        }else{
            $this->tableName($userId);
        }
        return DB::table($this->table)->where('user_id',$userId)->update([
            'is_del' => 1,
            'deleted_at' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Todo:: 获取资产总数
     * @param $assetsName
     * @return \Illuminate\Support\Collection
     */
    public function assetsSum($assetsName){
        $data = DB::table($this->table)
            ->where('name',$assetsName)
            ->select(DB::raw("SUM(total) as total,SUM(available) as available,SUM(freeze) as freeze"));
        $tables = $this->tables();
        unset($tables[0]);
        foreach ($tables as $key=>$val){
            $rowTable = DB::table($val)->where('name',$assetsName)
                ->select(DB::raw("SUM(total) as total,SUM(available) as available,SUM(freeze) as freeze"));
            $data->union($rowTable);
        }
        $total = $data;
        $available = $data;
        $freeze = $data;
//        $sum = $data->sum('available');
        $sum = [
            'total' => $total->sum('total'),
            'available' => $total->sum('available'),
            'freeze' => $total->sum('freeze'),
        ];
        return (object)$sum;
    }




}
